package net.hxz.modules.controller.frontEnd;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.hxz.modules.controller.BaseController;
import net.wy.commons.util.FileUtil;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件
 * @author lcs
 */
@Controller
@RequestMapping(value="/file")
public class FileController extends BaseController {
	
	/**
	 * 上传banner
	 * @return
	 */
	@RequestMapping(value = "/banner.json")
	public void banner(@RequestParam("file") MultipartFile file, ModelMap map) {
		//Map<String, Object> tmp = new HashMap<String, Object>();
		map.put("url", "/banner/"+FileUtil.upload(file, "/banner"));
		//map.put("json", new JSONObject(tmp).toString());
		//return "json";
	}
	
	/**
	 * 上传作品封面
	 * @return
	 */
	@RequestMapping(value = "/cover")
	public String cover(@RequestParam("file") MultipartFile file, ModelMap map) {
		Map<String, Object> tmp = new HashMap<String, Object>();
		tmp.put("url", "/cover/"+FileUtil.upload(file, "/cover"));
		map.put("json", new JSONObject(tmp).toString());
		return "json";
	}
	
	/**
	 * 上传图片
	 * @return
	 */
	@RequestMapping(value = "/image.json")
	public void image(@RequestParam("upload") MultipartFile file, ModelMap map) {
		map.put("url", "/image/"+FileUtil.upload(file, "/image"));
	}
	
	/**
	 * 上传LOGO
	 * @return
	 */
	@RequestMapping(value = "/logo")
	public String logo(@RequestParam("file") MultipartFile file, ModelMap map) {
		Map<String, Object> tmp = new HashMap<String, Object>();
		tmp.put("url", "/logo/"+FileUtil.upload(file, "/logo"));
		map.put("json", new JSONObject(tmp).toString());
		return "json";
	}
	
	/**
	 * 上传ckEditor图片
	 * @return
	 */
	@RequestMapping(value = "/ckImage.json")
	public void image(@RequestParam("upload") MultipartFile file, String CKEditorFuncNum, HttpServletRequest request, HttpServletResponse response,ModelMap map) throws IOException {
		String fileName = FileUtil.upload(file, "/image");
		
		//防止无端被html转义
		response.setContentType("text/html;charset=UTF-8");
		OutputStream outputStream = response.getOutputStream();
		outputStream.write("<script type=\"text/javascript\">".getBytes());
		String host =request.getRequestURL().toString().replaceAll("/file/ckImage.json", "");
		String cmd = "window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" +host+"/image/" + fileName + "','');";
		outputStream.write(cmd.getBytes());
		outputStream.write("</script>".getBytes());
		outputStream.close();
	}

}
